package com.eaoa.dao.pub;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.eaoa.vo.pub.PubCustomer;
import com.stony.core.dao.HibernateDataAccessObject;
import com.stony.core.exception.RunException;

/**
 * 
 * TODO To change the template for this generated type comment go to Window -
 * 
 * Preferences - Java - Code Style - Code Templates
 * 
 */

public class PubCustomerDAO extends HibernateDataAccessObject {

	public PubCustomerDAO() {

		super(PubCustomer.class);

	}

	protected void onDeleteTrigger(Object object) {

		super.onDeleteTrigger(object);

	}

	protected void onSaveOrUpdateTrigger(Object object) {

		super.onSaveOrUpdateTrigger(object);

	}

	protected void onSaveTrigger(Object object) {

		super.onSaveTrigger(object);

	}

	protected void onUpdateTrigger(Object object) {

		super.onUpdateTrigger(object);

	}

	public Long getAddressno(Long customerno) {

		PreparedStatement pstm = null;

		ResultSet rset = null;

		String sql = "SELECT addressno2 FROM eapt_customer WHERE customerno = ?";

		String sql1 = "SELECT addressno FROM eapt_customeraddress WHERE isavailable = 'Y' AND customerno = ?";

		String sql2 = "UPDATE eapt_customer SET addressno2 = ? WHERE customerno = ?";

		try {
			Connection conn = getSession().connection();

			pstm = conn.prepareStatement(sql);

			pstm.setLong(1, customerno.longValue());

			rset = pstm.executeQuery();

			if (rset.next()) {

				long addressno2 = rset.getLong(1);

				if (addressno2 > 0)
					return new Long(addressno2);

			}

			rset.close();
			pstm.close();

			pstm = conn.prepareStatement(sql1);

			pstm.setLong(1, customerno.longValue());

			rset = pstm.executeQuery();

			if (rset.next()) {

				long addressno = rset.getLong(1);

				rset.close();
				pstm.close();

				pstm = conn.prepareStatement(sql2);

				pstm.setLong(1, addressno);
				pstm.setLong(2, customerno.longValue());

				pstm.executeUpdate();

				return new Long(addressno);

			} else {

				throw new RunException("error.customer.noaddress");

			}

		} catch (SQLException e) {

			throw new RunException(e);

		} finally {

			try {
				if (rset != null)
					rset.close();
			} catch (SQLException e1) {
			}

			try {
				if (pstm != null)
					pstm.close();
			} catch (SQLException e1) {
			}

		}

	}

}
